//
//  UILabelViewController.swift
//  Example
//
//  Created by T AO on 2022/2/15.
//

import UIKit
import RxSwift
import RxCocoa

class UILabelViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let label = UILabel(frame: CGRect(x: 20, y: 100, width: 300, height: 100))
        view.addSubview(label)
        
        // 创建一个计时器（每0.1s发送一个索引数）
        let timer = Observable<Int>.interval(RxTimeInterval.milliseconds(100), scheduler: MainScheduler.instance)
        
        // 将已过去的时间格式化成想要的字符串，并绑定到 label 上
//        timer
//            .map { String(format: "%0.2d:%0.2d.%0.1d", [($0 / 600) % 600, ($0 % 600) / 10, $0 % 10]) }
//            .bind(to: label.rx.text)
//            .disposed(by: disposeBag)
        
        timer
            .map(formatTimeInterval)
            .bind(to: label.rx.attributedText)
            .disposed(by: disposeBag)
    }
    
    /// 将数字转成对应的富文本
    private func formatTimeInterval(ms: Int) -> NSMutableAttributedString {
        let string = String(format: "%0.2d:%0.2d.%0.1d", [(ms / 600) % 600, (ms % 600) / 10, ms % 10])
        
        let attributedString = NSMutableAttributedString(string: string)
        
        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!, range: NSRange(location: 0, length: 5))
        
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: 5))
        
        attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.orange, range: NSRange(location: 0, length: 5))
        
        return attributedString
    }

}
